package com.file;

import java.io.*;
/**
 * @Description: 字符流文件复制
 */
public class CharFileCopy {
    public static void main(String[] args) throws IOException {
        String srcPath = "f:/test/testRead.txt";
        String destPath = "f:/test/testWrite.txt";
        copyFile2(srcPath, destPath);
    }


    //使用字符流拷贝文件，有完善的异常处理
    public static void copyFile2(String path1, String path2) {
        Reader reader = null;
        Writer writer = null;
        try {
            // 打开流
            reader = new FileReader(path1);
            writer = new FileWriter(path2);

            // 进行拷贝
            int ch = -1;
            char [] arr=new char[1024];
            while ((ch = reader.read(arr)) != -1) {
                writer.write(ch);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭流，注意一定要能执行到close()方法，所以都要放到finally代码块中
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
